﻿CREATE procedure [dbo].[sp_PearlAccountNonMapped]
as

INSERT INTO PearlAccountMap
(AccountL14Desc, Leaf, LeafDescr, LineType)
SELECT DISTINCT
	Account14.[Description] as AccountL14Descr,
	AccountLeaf.Code as [Leaf],
	AccountLeaf.[Description] as [LeafDescr],
	'' LineType
	--ISNULL(LineType, 'Labor Cost, account sem mapeamento') as [PTSLine]
FROM [FinancePlanningAnalysis].dbo.Pearl
	INNER JOIN [FinancePlanningAnalysis].dbo.Scenario ON Scenario.Id = ScenarioId
	INNER JOIN [FinancePlanningAnalysis].dbo.PMFAccount AccountLeaf ON AccountLeafId = AccountLeaf.Id
		LEFT JOIN [FinancePlanningAnalysis].dbo.PMFAccount Account18 ON AccountL18Id = Account18.Id
		LEFT JOIN [FinancePlanningAnalysis].dbo.PMFAccount Account17 ON Account18.ParentId = Account17.Id
		LEFT JOIN [FinancePlanningAnalysis].dbo.PMFAccount Account16 ON Account17.ParentId = Account16.Id
		LEFT JOIN [FinancePlanningAnalysis].dbo.PMFAccount Account15 ON Account16.ParentId = Account15.Id
		LEFT JOIN [FinancePlanningAnalysis].dbo.PMFAccount Account14 ON Account15.ParentId = Account14.Id
	INNER JOIN [ftools.nam.nsroot.net].GocAttributes.dbo.vwGocRuleResultHierarchy ValidGocs on GocId = ValidGocs.Id
	INNER JOIN [ftools.nam.nsroot.net].GocAttributes.dbo.vwManagedSegmentHierarchy ManagedSegment on ManagedSegment.Id = ManagedSegmentId
	LEFT JOIN PTS.dbo.PearlAccountMap PearlMap ON PearlMap.Leaf = AccountLeaf.Code 
WHERE Scenario.[Description] = 'Actual Scenario'
	AND (ManagedSegment.CodeLevel6 IN (6719)
	OR ManagedSegment.CodeLevel7 IN (22941))
	AND LineType IS NULL